package com.platform.module.admin.controller;

import com.platform.module.common.base.BaseReq;
import com.platform.module.common.base.CodeEnum;
import com.platform.module.common.base.CommonResp;
import com.platform.module.common.base.NoNeedLogin;
import com.platform.module.common.constant.CacheConstant;
import com.platform.module.common.exception.CommonException;
import com.platform.module.common.redis.CacheClient;
import com.platform.module.common.utils.TokenGenerator;
import com.platform.module.dao.entity.TokenRecord;
import com.platform.module.dao.mapper.TbUserMapper;
import com.platform.module.dao.mapper.TokenMapper;
import com.platform.module.pojo.UserRecord;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Long
 * @since 2024/11/14 18:02
 **/
@Slf4j
@RestController
@Tag(
        name = "测试接口",
        description = "测试接口"
)
@RequestMapping("/data/test")
@AllArgsConstructor
public class DataTestController {

    private final TbUserMapper tbUserMapper;
    private final TokenMapper tokenMapper;
    private final CacheClient cacheClient;

    @GetMapping("/aa.api")
    public CommonResp<UserRecord> aa(@Parameter(hidden = true) BaseReq req,
                                     @RequestParam Long userId) {
        log.info("cmsId:{}", req.getAppId());
        UserRecord userRecord = tbUserMapper.findUserByUid(userId);
        if (ObjectUtils.isEmpty(userRecord)) {
            throw new CommonException(CodeEnum.账号不存在);
        }
        return CommonResp.ok(userRecord);
    }

    @GetMapping("/getToken.api")
    @NoNeedLogin
    @Operation(summary = "获取token接口", description = "获取token接口")
    public CommonResp<String> getToken(@Parameter(hidden = true) BaseReq req,Long userId) {
        String accessToken = TokenGenerator.createToken(userId + "", "ZJc5vCkB1jLdSzKfBJrmwGjY");
        TokenRecord tbToken = new TokenRecord();
        tbToken.setCaccesstoken(accessToken);
        tbToken.setIexpiresin(1209600000L);
        tbToken.setUserId(userId);
        int res = this.tokenMapper.addToken(tbToken);

        this.cacheClient.setDays(CacheConstant.CMS_USER_TOKEN + accessToken, accessToken, 90L);
        if (res != 1) {
            log.error("注册token失败,token：{},userId:{} ", tbToken, userId);
            throw new RuntimeException("注册token失败 ");
        } else {
            log.info("注册新token成功,uid:{}", userId);
            return CommonResp.ok("success",tbToken.getCaccesstoken());
        }
    }

}
